<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/1/4
 * Time: 上午10:10
 */

namespace app\admin\service;

use app\admin\facade\User;
use thans\auth\model\AuthGroupAccessModel;
use app\user\model\UserModel;
use think\Exception;
use think\Db;
use app\user\facade\User as BaseUser;

class UserService
{
    /**
     *
     * @method 根据类型查询用户
     * @version
     * @User: bevan
     * @param
     * @return
     */
    public function getList($data)
    {
        $userModel = new UserModel();
        $res = $userModel->getList($data['page'], $data['limit'], $data['type'],$data['keyword']);
        if ($res) {
            return $res;
        } else {
            return ['code' => 4001, 'msg' => '查询失败', 'data' => []];
        }
    }

    /**
     * 获取单个用户 （管理员）
     * @method
     * @version
     * @User: Thans
     * @param $id
     * @return
     */
    public function index($id)
    {
        $user = UserModel::where('id', $id)->field('user_pass,last_login_ip',true)->find();

        return ['code'=>1001,'msg'=>'获取成功','data'=>$user];
    }


    /**
     * 编辑用户 (单个用户信息)
     * @method
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function edit($id)
    {
        $userModel = new UserModel();

        $user = $userModel->userRuleDetail($id);

        if ($user === false) {
            return ['code' => 4001, 'msg' => '查询失败', 'data' => []];
        }
        return ['code' => 1001, 'msg' => '查询成功', 'data' => $user];
    }

    /**
     * 添加会员用户 （管理员操作）
     * @method
     * @version
     * @User: Thans
     * @param $id
     * @return
     */
    public function add($data)
    {
        //如果 手机号码  和 邮箱填了 则验证是否规范
        //校验唯一性
        $userModel = new UserModel();

        if($data['user_email']){
            if(!cmf_validate_email($data['user_email'])){
                return ['code'=>4001,'msg'=>'请填写正确的邮箱','data'=>[]];
            }
        }else{
            unset($data['user_email']);
        }

        if($data['mobile']){
            if(!cmf_validate_mobile($data['mobile'])){
                return ['code'=>4001,'msg'=>'请填写正确的手机号码','data'=>[]];
            }
        }else{
            unset($data['mobile']);
        }

        $validate_msg = UserModel::checkUnique($data);

        if($validate_msg !== true){
            return ['code'=>4001,'msg'=>$validate_msg,'data'=>[]];
        }

        //创建会员
        if($data['status'] === ''){
           $data['status'] = 0; // 未传用户创建状态 为 禁用
        }
        $data['user_pass'] = cmf_crypt_password($data['user_pass']);
        $data['user_type'] = 2; //会员

        $user = UserModel::create($data,true);

        if($user === false){
            return ['code'=>4001,'msg'=>'创建失败','data'=>[]];
        }

        return ['code'=>1001,'msg'=>'创建成功','data'=>[]];
    }


    /**
     *
     * @method 更新用户信息 （管理员操作 使用）
     * @version
     * @User: bevan
     * @param $id
     * @param $data
     * @return
     */
    public function update($id, $data)
    {
        $user = UserModel::get($id);

        if($user->user_login == $data['user_login']){
            //不需要更新 不需要校验
            unset($data['user_login']);
        }else{
            //需要更新 需要校验唯一性
            $user->user_login = $data['user_login'];
        }

        if(isset($data['user_pass']) && $data['user_pass']){
            //需要更新密码
            $user->user_pass = cmf_crypt_password($data['user_pass']);
        }

        if(isset($data['user_email']) && $data['user_email']){
            //需要更新邮箱
            //校验邮箱合法
            if(!cmf_validate_email($data['user_email'])){
                return ['code'=>4001,'msg'=>'邮箱格式错误','data'=>[]];
            }
            $user->user_email = $data['user_email'];
        }else{
            unset($data['user_email']);
        }

        if(isset($data['mobile']) && $data['mobile']){
            //需要更新手机号码
            //校验手机合法性
            if(!cmf_validate_mobile($data['mobile'])){
                return ['code'=>4001,'msg'=>'手机号码格式不正确','data'=>[]];
            }
            $user->mobile = $data['mobile'];
        }else{
            unset($data['mobile']);
        }

        if(isset($data['status']) && $data['status'] !== ''){
            //需要更新状态
            $user->status = $data['status'];
        }
        //校验唯一性
        $validate_msg = UserModel::checkUnique($data, $user->id);

        if($validate_msg !== true){
            return ['code'=>4001,'msg'=>$validate_msg,'data'=>[]];
        }

        $user->save();

        return ['code'=>1001,'msg'=>'更新成功','data'=>[]];
    }

    /**
     *获取管理员
     * @method
     * @version
     * @User: bevan
     * @return
     */
    public function getAdmins($data)
    {
        $userModel = new UserModel();
        $res = $userModel->getList($data['page'], $data['limit'], '1',$data['keyword']);
        if ($res) {
            return $res;
        } else {
            return ['code' => 4001, 'msg' => '查询失败', 'data' => []];
        }
    }

    /**
     *
     * @method 添加管理员
     * @version
     * @User: bevan
     * @return
     */
    public function addAdmin($data)
    {
        //验证该邮箱或该用户名是否唯一
        $result = UserModel::checkUnique($data);

        if ($result !== true) {
            return ['code' => 4003, 'msg' => $result, 'data' => []];
        }

        $data['user_type'] = 1; //管理员
        $data['sex'] = 0; //默认管理员性别
        $data['user_pass'] = cmf_crypt_password($data['user_pass']); //密码加密

        //添加
        Db::startTrans();
        try {
            $user = UserModel::create($data, true);

            //增加管理权限组
            AuthGroupAccessModel::where('uid', $user->id)->delete();

            AuthGroupAccessModel::create([
                'uid' => $user->id,
                'group_id' => $data['group_id']
            ]);

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 4001, 'msg' => $e->getMessage(), 'data' => []];
        }

        return ['code' => 1001, 'msg' => '创建成功', 'data' => []];
    }

    /**
     *
     * @method
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function getAdminInfo($id)
    {
        $user = UserModel::where('id', $id)
            ->alias('u')
            ->field('aga.*, u.id,u.user_login, u.user_email,u.last_login_time,u.status')
            ->join('auth_group_access aga', 'u.id = aga.uid', 'left')
            ->find();

        if ($user == false) {
            return ['code' => 4001, 'msg' => '获取失败', 'data' => []];
        }


        return ['code' => 1001, 'msg' => '获取成功', 'data' => $user];
    }


    /**
     *
     * @method  更新管理员的信息
     * @version
     * @User: bevan
     * @param $data
     * @return
     */
    public function updateAdmin($data)
    {
        //密码是否为空
        if ($data['user_pass']) {
            //加密
            $data['user_pass'] = cmf_crypt_password($data['user_pass']);
        } else {
            if (isset($data['user_pass'])) {
                unset($data['user_pass']);
            }
        }

        //校验唯一性
        $validate_msg = UserModel::checkUnique($data, $data['id']);

        if($validate_msg !== true){
            return ['code'=>4001,'msg'=>$validate_msg,'data'=>[]];
        }

        Db::startTrans();
        try {

            $userModel = new UserModel();
            $userModel->allowField(true)->save($data, ['id' => $data['id']]);

            //更新权限组
            AuthGroupAccessModel::where('uid', $data['id'])
                ->update([
                    'group_id' => $data['group_id']
                ]);

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 4001, 'msg' => $e->getMessage(), 'data' => []];
        }

        return ['code' => 1001, 'msg' => '更新成功', 'data' => []];
    }

    /**
     *
     * @method 删除管理员（硬删除）
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function delAdmin($id)
    {
        if($id == 1){
            return ['code'=>4001,'msg'=>'不允许删除超级管理员','data'=>[]];
        }
        //校验是否是管理员
        $where[] = ['id', '=',(int)$id];
        $where[] = ['user_type','=', 1]; //必须是管理员
        Db::startTrans();
        try {
            UserModel::where($where)->delete();

            AuthGroupAccessModel::where('uid', $id)->delete();

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();

            return ['code' => 4001, 'msg' => $e->getMessage(), 'data' => []];
        }

        return ['code'=>1001,'msg'=>'删除成功','data'=>[]];
    }

    /**
     *
     * @method  解禁
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function toggle($id)
    {
        $user = UserModel::where('id', $id)->find();
        if(!$user){
            return ['code' => 4001, 'msg' => '用户不存在', 'data' => []];
        }
        $status = $user['status'];
        if($status){
            UserModel::where('id', $id)->setField('status',0);
            return ['code' => 1001, 'msg' => '封禁成功', 'data' => []];
        }else{
            UserModel::where('id', $id)->setField('status',1);
            return ['code' => 1001, 'msg' => '解封成功', 'data' => []];
        }
    }

    /**
     *
     * @method 搜索
     * @version
     * @User: bevan
     * @param $name
     * @return
     */
    public function searchUser($name)
    {
        $users = UserModel::where('user_login','like','%' . $name . '%')->select();

        return ['cdoe'=>1001,'msg'=>'搜索成功','data'=>$users];
    }

}